import socket
import netifaces
from flask import current_app
import datetime

class NetworkService:
    """网络服务类"""
    
    @staticmethod
    def get_network_info(refresh=False):
        """
        获取网络信息
        
        Args:
            refresh: 是否强制刷新
            
        Returns:
            dict: 网络信息
        """
        # 获取主机名
        hostname = socket.gethostname()
        
        # 获取IP地址和MAC地址
        ip_address = None
        mac_address = None
        interface = None
        
        try:
            # 获取所有网络接口
            interfaces = netifaces.interfaces()
            
            # 过滤掉回环接口
            valid_interfaces = [i for i in interfaces if i != 'lo' and not i.startswith('docker')]
            
            for iface in valid_interfaces:
                addrs = netifaces.ifaddresses(iface)
                
                # 获取IPv4地址
                if netifaces.AF_INET in addrs:
                    ip_info = addrs[netifaces.AF_INET][0]
                    if 'addr' in ip_info and ip_info['addr'] != '127.0.0.1':
                        ip_address = ip_info['addr']
                        interface = iface
                        break
                        
            # 获取MAC地址
            if interface and netifaces.AF_LINK in netifaces.ifaddresses(interface):
                mac_info = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]
                if 'addr' in mac_info:
                    mac_address = mac_info['addr']
        except Exception as e:
            current_app.logger.error(f"获取网络信息失败: {str(e)}")
            
        # 如果没有找到有效的IP地址，尝试使用socket连接获取
        if not ip_address:
            try:
                s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                s.connect(("8.8.8.8", 80))
                ip_address = s.getsockname()[0]
                s.close()
            except Exception as e:
                current_app.logger.error(f"获取IP地址失败: {str(e)}")
                ip_address = "127.0.0.1"
        
        # 返回网络信息字典
        return {
            'ip_address': ip_address,
            'hostname': hostname,
            'mac_address': mac_address or "00:00:00:00:00:00",
            'interface': interface or "eth0",
            'created_at': datetime.datetime.now().isoformat()
        }
    
    @staticmethod
    def get_qr_code_url():
        """
        获取二维码URL
        
        Returns:
            str: 二维码URL
        """
        network_info = NetworkService.get_network_info()
        ip_address = network_info.get('ip_address')
        
        if not ip_address:
            return None
            
        port = current_app.config.get('PORT', 5000)
        url = f"http://{ip_address}:{port}"
        
        # 使用外部服务生成二维码
        qr_code_url = f"https://api.qrserver.com/v1/create-qr-code/?size=200x200&data={url}"
        return qr_code_url 